package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.dto.EmpDTO;
import com.example.mapper.EmpMapper;
import com.example.pojo.Emp;
import com.example.pojo.PageBean;
import com.example.service.EmpService;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmpServiceImpl extends ServiceImpl<EmpMapper, Emp> implements EmpService {

    //使用MybatisPlus自带分页插件进行条件分页查询
    @Override
    public PageBean<Emp> find(EmpDTO empDTO) {
        //1.分页条件
        Page<Emp> p = Page.of(empDTO.getPage(), empDTO.getPageSize());

        //2.排序条件
        p.addOrder(new OrderItem("update_time", false));

        //3.构造查询条件
        String name = empDTO.getName();
        Short gender = empDTO.getGender();
        LocalDate begin = empDTO.getBegin();
        LocalDate end = empDTO.getEnd();

        LambdaQueryWrapper<Emp> wrapper = new LambdaQueryWrapper<Emp>()
                //模糊匹配
                .like(name != null && name != "", Emp::getName, name)
                //精确匹配
                .eq(gender != null, Emp::getGender, gender)
                .between(begin != null && end != null, Emp::getEntrydate, begin, end);

        //4.分页查询
        page(p, wrapper);

        //5.获取查询结果
        long total = p.getTotal();
        List<Emp> list = p.getRecords();

        //6.封装结果返回
        return PageBean.of(total, list);
    }

    @Override
    public void updateEmp(Emp emp) {
        emp.setUpdateTime(LocalDateTime.now());
        updateById(emp);
    }
}
